package com.huifaapp.mall.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.EvaluateImageAdapter;
import com.huifaapp.mall.afinal.JSConstants;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.base.activity.BaseTitleBarActivity;
import com.huifaapp.mall.base.basemvp.IPresenter;
import com.huifaapp.mall.bean.GoodsDateBean;
import com.huifaapp.mall.bean.MessageEvent;
import com.huifaapp.mall.bean.UploadImagBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.GlideUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.tencent.mm.opensdk.utils.Log;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.PhotoPreview;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;


/**
 * author: wangZ
 * date：2017/9/6 17:02
 * FileName：EvaluateActivity
 * description：评价页面
 */

public class EvaluateActivity extends BaseTitleBarActivity {

    public static final String KEY_PRODUCT_ID = "PRODUCT_ID";
    public static final String KEY_PINGjIA_ID = "PINGjIA_ID";

    public static final String DEFAULT_ADD = "default_add";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_xianJia)
    TextView tvXianJia;
    @BindView(R.id.tv_yuanJia)
    TextView tvYuanJia;
    @BindView(R.id.rl_jiaqian)
    RelativeLayout rlJiaqian;
    @BindView(R.id.tv_pingJiaNum)
    TextView tvPingJiaNum;
    @BindView(R.id.tv_haoPin)
    TextView tvHaoPin;
    @BindView(R.id.rl_pingjia)
    RelativeLayout rlPingjia;
    @BindView(R.id.gv_gridview)
    GridView gvGridview;
    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.tv_tijiao)
    TextView tvTijiao;  @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.mt_content)
    MaterialEditText mtContent;
    @BindView(R.id.mr_xingxing)
    MaterialRatingBar mrXingxing;
    private List<Integer> successReqCodes = new ArrayList<>();
    private List<Integer> errorReqCodes = new ArrayList<>();

    private EvaluateImageAdapter adapter;
    private ArrayList<String> mpSelectedPhotos = new ArrayList<>();
    private ArrayList<String> mChuFangPhotos = new ArrayList<>();
    private String conten,starNum;
    private  StringBuffer imageUrlSB = new StringBuffer();


    private  String productId,pingJiaID;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_evaluate;
    }

    public static final int START_MP_CODE = 2001;

    @Override
    protected void initData(Bundle bundle) {

        setTtle("商品评价");
        productId =   bundle.getString(KEY_PRODUCT_ID);
        pingJiaID =   bundle.getString(KEY_PINGjIA_ID);

        getGoodsDate(productId);


        adapter = new EvaluateImageAdapter(mContext);
        gvGridview.setAdapter(adapter);
        mpSelectedPhotos.add(DEFAULT_ADD);
        adapter.setNewData(mpSelectedPhotos);
        gvGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String imgs = (String) parent.getItemAtPosition(position);
                if (DEFAULT_ADD.equals(imgs)) {
                    mpSelectedPhotos.remove(DEFAULT_ADD);
                    PhotoPicker.builder()
                            .setPhotoCount(3)
                            .setGridColumnCount(4)
                            .setShowCamera(true)
                            .setSelected(mpSelectedPhotos)
                            .start(mContext, START_MP_CODE);
                } else {
                    mpSelectedPhotos.remove(DEFAULT_ADD);
                    PhotoPreview.builder()
                            .setPhotos(mpSelectedPhotos)
                            .setCurrentItem(position)
                            .start(mContext, START_MP_CODE);
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == PhotoPickerActivity.RESULT_OK && requestCode == START_MP_CODE) {
            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);


                resSelectMpPhotos(photos);
                mChuFangPhotos.clear();
                mChuFangPhotos.addAll(photos);
            }
        }
    }

    private void resSelectMpPhotos(List<String> photos) {
        if (null != photos) {


            mpSelectedPhotos.clear();
            mpSelectedPhotos.addAll(photos);


            mpSelectedPhotos.add(DEFAULT_ADD);
            adapter.setNewData(mpSelectedPhotos);
        }
    }

    @Override
    protected IPresenter onLoadPresenter() {
        return null;
    }


    @OnClick({R.id.tv_haoPin, R.id.tv_tijiao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_haoPin:
                break;
            case R.id.tv_tijiao:
                yanzheng();
                break;
        }
    }

            int num = 0;
    /**
     * 上传图片
     *
     * @param imgUrls
     * @param code
     */
    private void uploadImages(final List<String> imgUrls, final int code) {

        final LoadingDialog dialog  = new LoadingDialog(mContext);
        if (imgUrls != null && imgUrls.size() > 0) {
            dialog.show();
            for (int i = 0; i < imgUrls.size(); i++) {
                final int e = i;
                ApiManager.getInstance()
                        .uploadImage2(imgUrls.get(i) )
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<UploadImagBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(UploadImagBean value) {

                                Log.e("数据","上传图片"+value);
//                                LogUtils.e(value.toString());
                                imageUrlSB.append(value.getData().getUrl() + ",");
//                                LogUtils.e("jpg"+value.getFileName());
                            }

                            @Override
                            public void onError(Throwable e) {
                                LogUtils.e("onError", "onError");
                                num++;
                                if (num == imgUrls.size()) {
                                    dialog.dismiss();
                                    evaluationGoods();

                                }
                            }

                            @Override
                            public void onComplete() {
                                num++;
                                if (num == imgUrls.size()) {
                                    dialog.dismiss();
                                    evaluationGoods();
                                }
                            }
                        });


            }
        } else {
            evaluationGoods();
        }
    }

    private void evaluationGoods() {
        num=0;
        String imgs =null;

        if (imageUrlSB.length()>0) {
            imgs=  imageUrlSB.substring(0, imageUrlSB.length()-1).toString();
        }
        if(conten.equals("")||conten.equals(null)||conten.equals("null")) {
                Toast.makeText(EvaluateActivity.this,"商品评价不能为空",Toast.LENGTH_SHORT).show();
        }else{
            Log.e("数据","评价"+conten+imgs+ pingJiaID+ starNum+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
//            ApiManager
//                    .getInstance()
//                    .getApiServer()
//                    .evaluationGoods(conten, imgs, pingJiaID, starNum, SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
//                    .compose(ApiManager.<String>handlResult())
//                    .subscribe(new ObserverCallback<String>(mContext) {
//                        @Override
//                        protected void onSuccessful(String resp) {
//                            imageUrlSB.setLength(0);
//                            ToastUtils.showShortSafe("评价成功");
//                            EventBus.getDefault().post(new MessageEvent().setMesg(ApiManager.BASE_HTML_URL + JSConstants.HTML_PINGJIA_WANCHENG));
//                            tvHaoPin.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    finish();
//                                }
//                            }, 1500);
//                        }
//
//                        @Override
//                        protected void onError(String code, String errMsg) {
//                            imageUrlSB.setLength(0);
//                        }
//                    });
        }
    }




    private  void  getGoodsDate(String id){

//        ApiManager
//                .getInstance()
//                .getApiServer()
//                .getGoodsDate(id)
//                .compose(ApiManager.<GoodsDateBean>handlResult())
//                .subscribe(new ObserverCallback<GoodsDateBean>(mContext) {
//                    @Override
//                    protected void onSuccessful(GoodsDateBean resp) {
//                        initGoodsDate(resp.getProduct());
//                    }
//
//                    @Override
//                    protected void onError(String code, String errMsg) {
//
//                    }
//                });

    }
    private  void  initGoodsDate(GoodsDateBean.ProductBean bean){
        GlideUtils.loadImageView(getApplicationContext(),bean.getMainImageUrl(),ivImage);

        tvTitle.setText(bean.getName());
        tvXianJia.setText("¥"+bean.getProductPrice());

        tvYuanJia.setText("¥"+bean.getProductOrginPrice());
        tvYuanJia.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
        tvPingJiaNum.setText(bean.getTotalFeedback()+"条评价");
        tvHaoPin.setText("好评"+bean.getPercentFeedback()+"%");
        tvNum.setText("销量："+bean.getTotalSales());


    }
 private  void yanzheng(){
     conten = mtContent.getText().toString();
     starNum = (int)mrXingxing.getRating  ()+"";
     if (mrXingxing.getRating()==0) {

         ToastUtils.showShortSafe("请选择级别");
         return;
     }
     uploadImages(mChuFangPhotos, 33);

 }
}
